package com.guigu.qingcheng.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.guigu.common_util.pojo.utils.Result;
import com.guigu.qingcheng.entity.Goods;
import com.guigu.qingcheng.entity.TbSku;
import com.guigu.qingcheng.entity.TbSpu;
import com.guigu.qingcheng.service.GoodsServiceFeign;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.annotation.Resource;
import java.io.File;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/item")
public class ItemController {

    @Resource
    private GoodsServiceFeign goodsServiceFeign;


    @Autowired
    private TemplateEngine templateEngine;

//    @Value("${pagePath}")
//    private static final String destPath = "D:/qingcheng/qiantaiyemian/item/";

    @Value("${pagePath}")
    private String pagePath;

    @GetMapping("/createPage")
    public void createPage(String id){
        // 查询商品信息
        Goods goods = goodsServiceFeign.findGoodsById(id);
        // 获取spu信息
        TbSpu spu = goods.getSpu();
        // 获取sku信息
        List<TbSku> skuList = goods.getSkuList();
        // 查询商品分类
        List<String> categoryList = new ArrayList<>();
        categoryList.add(goodsServiceFeign.findById2(spu.getCategory1Id()).getName());//一级分类
        categoryList.add(goodsServiceFeign.findById2(spu.getCategory2Id()).getName());//二级分类
        categoryList.add(goodsServiceFeign.findById2(spu.getCategory3Id()).getName());//三级分类

        // 数据模型添加SKU图片列表和SPU图片列表

        //生成SKU地址列表
        Map urlMap = new HashMap();
        for (TbSku sku1:skuList) {
            if ("1".equals(spu.getStatus())){
                //对规格json字符串进行排序
                String specJson = JSON.toJSONString(JSON.parseObject(sku1.getSpec()), SerializerFeature.MapSortField);
                urlMap.put(specJson,sku1.getId()+".html");
            }
        }

        // 创建页面（每个sku一个页面）
        for(TbSku sku: skuList){
            // 1.上下文
            Context context = new Context();
            // 创建数据模型
            Map<String, Object> dataModel = new HashMap<>();
            dataModel.put("spu",spu);
            dataModel.put("sku", sku);
            dataModel.put("categoryList",categoryList);
            dataModel.put("skuImages", sku.getImages().split(",")); // sku图片列表
            dataModel.put("spuImages", spu.getImages().split(",")); // spu图片列表
            // 数据模型添加规格和参数
            Map paraItems = JSON.parseObject(spu.getParaItems()); // SPU参数列表
            dataModel.put("paraItems", paraItems);
            Map specItems = JSON.parseObject(sku.getSpec()); // 当前SKU规格
            dataModel.put("specItems", specItems);
            Map<String,List> specMap = (Map) JSON.parse(spu.getSpecItems());
            for (String key:specMap.keySet()){ // 循环规格选项值
                List<String> list = specMap.get(key);
                List<Map> mapList = new ArrayList<>();
                for (String value: list){
                    Map map = new HashMap();
                    map.put("option",value);
                    if (specItems.get(key).equals(value)){//判断此规格组合是否是当前SKU的，标记选中状态
                        map.put("checked",true);
                    } else {
                        map.put("checked",false);
                    }
                    mapList.add(map);
                    // 商品详细页地址
                    Map spec = JSON.parseObject(sku.getSpec());//当前SKU规格
                    spec.put(key,value);
                    String specJson = JSON.toJSONString(spec,SerializerFeature.MapSortField);
                    map.put("url",urlMap.get(specJson));
                }
                specMap.put(key,mapList);
            }
            dataModel.put("specMap", specMap);


            context.setVariables(dataModel);
            // 准备文件
            File dir = new File(pagePath);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            File dest = new File(dir,sku.getId() + ".html");
            // 生成页面
            try {
                PrintWriter writer = new PrintWriter(dest, "UTF-8");
                templateEngine.process("item", context, writer);
                System.out.println("生成页面："+sku.getId()+".html");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @GetMapping("/findByIdPrice")
    public Result findByIdPrice(@RequestParam("skuId") String skuId){
        System.out.println("sssssssssssssssssss");
        return goodsServiceFeign.findByIdPrice(skuId);
    }


    @RabbitListener(queues = "queue.sjxx")
    public void createPage1(Message message){
        String id = new String(message.getBody());
        // 查询商品信息
        Goods goods = goodsServiceFeign.findGoodsById(id);
        // 获取spu信息
        TbSpu spu = goods.getSpu();
        // 获取sku信息
        List<TbSku> skuList = goods.getSkuList();
        // 查询商品分类
        List<String> categoryList = new ArrayList<>();
        categoryList.add(goodsServiceFeign.findById2(spu.getCategory1Id()).getName());//一级分类
        categoryList.add(goodsServiceFeign.findById2(spu.getCategory2Id()).getName());//二级分类
        categoryList.add(goodsServiceFeign.findById2(spu.getCategory3Id()).getName());//三级分类

        // 数据模型添加SKU图片列表和SPU图片列表

        //生成SKU地址列表
        Map urlMap = new HashMap();
        for (TbSku sku1:skuList) {
            if ("1".equals(spu.getStatus())){
                //对规格json字符串进行排序
                String specJson = JSON.toJSONString(JSON.parseObject(sku1.getSpec()), SerializerFeature.MapSortField);
                urlMap.put(specJson,sku1.getId()+".html");
            }
        }

        // 创建页面（每个sku一个页面）
        for(TbSku sku: skuList){
            // 1.上下文
            Context context = new Context();
            // 创建数据模型
            Map<String, Object> dataModel = new HashMap<>();
            dataModel.put("spu",spu);
            dataModel.put("sku", sku);
            dataModel.put("categoryList",categoryList);
            dataModel.put("skuImages", sku.getImages().split(",")); // sku图片列表
            dataModel.put("spuImages", spu.getImages().split(",")); // spu图片列表
            // 数据模型添加规格和参数
            Map paraItems = JSON.parseObject(spu.getParaItems()); // SPU参数列表
            dataModel.put("paraItems", paraItems);
            Map specItems = JSON.parseObject(sku.getSpec()); // 当前SKU规格
            dataModel.put("specItems", specItems);
            Map<String,List> specMap = (Map) JSON.parse(spu.getSpecItems());
            for (String key:specMap.keySet()){ // 循环规格选项值
                List<String> list = specMap.get(key);
                List<Map> mapList = new ArrayList<>();
                for (String value: list){
                    Map map = new HashMap();
                    map.put("option",value);
                    if (specItems.get(key).equals(value)){//判断此规格组合是否是当前SKU的，标记选中状态
                        map.put("checked",true);
                    } else {
                        map.put("checked",false);
                    }
                    mapList.add(map);
                    // 商品详细页地址
                    Map spec = JSON.parseObject(sku.getSpec());//当前SKU规格
                    spec.put(key,value);
                    String specJson = JSON.toJSONString(spec,SerializerFeature.MapSortField);
                    map.put("url",urlMap.get(specJson));
                }
                specMap.put(key,mapList);
            }
            dataModel.put("specMap", specMap);


            context.setVariables(dataModel);
            // 准备文件
            File dir = new File(pagePath);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            File dest = new File(dir,sku.getId() + ".html");
            // 生成页面
            try {
                PrintWriter writer = new PrintWriter(dest, "UTF-8");
                templateEngine.process("item", context, writer);
                System.out.println("生成页面："+sku.getId()+".html");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @RabbitListener(queues = "queue.xjxx")
    public void removePage(Message message) {
        String id = new String(message.getBody());
        // 查询商品信息
        Goods goods = goodsServiceFeign.findGoodsById(id);
        // 获取spu信息
        TbSpu spu = goods.getSpu();
        // 获取sku信息
        List<TbSku> skuList = goods.getSkuList();
        for (TbSku sku1:skuList) {
            if ("1".equals(spu.getStatus())){
                File file = new File(pagePath+sku1.getId()+".html");
                if (file.isFile() && file.exists()){
                    System.out.println(sku1.getId()+".html");
                    file.delete();
                }
            }
        }

    }

}
